// 导入数据库
const db = require('../db/index');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../config')

// 注册
exports.register = (req, res) => {
  // 获取提交的数据信息
  const info = req.body;
  if (!info.account || !info.password) {
    return res.send({ code: 400, msg: '用户名或密码不合法' });
  }
  // 查询用户名是否被占用
  const sqlStr = 'select * from users where account = ?';
  db.query(sqlStr, info.account, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: err.message });
    }
    // 如果查询结果的数组长度不为0，则这个账号已存在
    if (results.length > 0) {
      return res.send({ code: 200, msg: '用户名被占用', isExist: true });
    }
    info.password = bcrypt.hashSync(info.password, 10); // 对密码加密
    const sql = 'insert into users set ?';
    db.query(sql, { account: info.account, password: info.password }, (err, results) => {
      if (err) {
        return res.send({ code: 500, msg: err.message });
      }
      if (results.affectedRows !== 1) {
        return res.send({ code: 500, msg: '未知错误，请联系管理员' });
      }
      res.send({ code: 200, msg: '注册成功' });
    });
  });
}

// 登录
exports.login = (req, res) => {
  const info = req.body;
  const sqlStr = 'select * from users where account = ?';
  db.query(sqlStr, info.account, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: err.message });
    }
    if (results.length !== 1) {
      return res.send({ code: 500, msg: '账号不存在' });
    }
    // 拿着用户输入的密码,和数据库中存储的密码进行对比
    const compareResult = bcrypt.compareSync(info.password, results[0].password)
    // 如果对比的结果等于 false, 则证明用户输入的密码错误
    if (!compareResult) {
      return res.send({ code: 401, msg: '密码错误' });
    }
    const user = { ...results[0], password: '' };
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: '10h', // token 有效期为 10 个小时
    })
    db.query(`select * from users where account = '${info.account}'`, (err, user) => {
      res.send({
        code: 200,
        msg: '登录成功',
        // 为了方便客户端使用 Token，在服务器端直接拼接上 Bearer 的前缀
        token: 'Bearer ' + tokenStr,
        userId: user[0].id
      })
      // 登录成功，生成 Token 字符串
    })
  })
}

// 写帖子
exports.write = (req, res) => {
  const info = req.body;
  info.type = info.type.join(',');
  const sql = 'insert into articles set ?';
  if (!info.title || !info.description || !info.content || !info.type || !info.time || !info.createdBy) {
    return res.send('请填写完整信息');
  }
  db.query(`select * from users where id = ${info.createdBy}`, (err, _results) => {
    // console.log(results[0].nickname);
    let author = _results[0].nickname;
    db.query(sql, { title: info.title, description: info.description, content: info.content, type: info.type, time: info.time, createdBy: info.createdBy, author: author }, (err, results) => {
      if (err) {
        return res.send({ code: 500, msg: err.message });
      }
      if (results.affectedRows !== 1) {
        return res.send({ code: 500, msg: '未知错误，请联系管理员' });
      }
      res.send({ code: 200, msg: '发表成功' });
    });
  })
}

// 更新帖子
exports.Rewrite = (req, res) => {
  const info = req.body;
  info.type = info.type.join(',');
  console.log(info);
  const sqlStr = `update articles set ? where id = ${info.id}`;
  db.query(sqlStr, { title: info.title, description: info.description, content: info.content, type: info.type, time: info.time }, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: err.message });
    }
    if (results.affectedRows !== 1) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
    res.send({ code: 200, msg: '更新成功' });
  })
}

// 获取帖子列表
exports.getArticles = (req, res) => {
  const info = req.query;
  if (info.type == 0) {
    info.type = '';
  }
  info.type = '"%' + info.type + '%"';
  const sql = `select * from articles where type like ${info.type}`;
  // "%2%"
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: err.message });
    }
    res.send({ code: 200, msg: '获取帖子成功', data: results })
  })
}

// 获取该用户所有信息
exports.getUserInfo = (req, res) => {
  const info = req.query;
  const sql = 'select * from users where id = ?';
  db.query(sql, info.id, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: err.message });
    }
    res.send({ code: 200, msg: '获取用户信息成功', data: results })
  })
}

// 修改个人信息
exports.changeUserInfo = (req, res) => {
  const info = req.body;
  if (!info.nickname || !info.id || !info.age || !info.gender || !info.school || !info.job) {
    return res.send({ code: 400, msg: '请输入完整信息' });
  }
  const sqlStr = `update users set ? where id = ${info.id}`;
  db.query(sqlStr, { nickname: info.nickname, age: info.age, gender: info.gender, school: info.school, job: info.job }, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
    res.send({ code: 200, msg: '更新成功', data: results })
  });
}

// 文章、作者累计被浏览次数
exports.beSeen = (req, res) => {
  const info = req.body;
  if (!info.id || !info.createdBy) {
    return res.send({ code: 400, msg: '请输入完整信息' });
  }
  const sqlStr = `update articles set look = look + 1 where id = ${info.id};\nupdate users set beSeen = beSeen + 1 where id = ${info.createdBy};`;
  db.query(sqlStr, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
    res.send({ code: 200, msg: '更新成功', data: results })
  });
}

// 点赞功能
exports.praise = (req, res) => {
  const info = req.body;
  let sqlStr;
  if (info.flag == true) {
    // 点赞
    sqlStr = `update articles set likes = likes + 1 where id = ${info.id};\nupdate users set beLiked = beLiked + 1 where id = ${info.createdBy};`
  } else {
    // 取消赞
    sqlStr = `update articles set likes = likes - 1 where id = ${info.id};\nupdate users set beLiked = beLiked - 1 where id = ${info.createdBy};`
  }
  db.query(sqlStr, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
    res.send({ code: 200, msg: '谢谢您的点赞~', data: results })
  })
}

// 获得这篇帖子的所有信息 
exports.getArticleInfo = (req, res) => {
  const info = req.query;
  const sqlStr = `select * from articles where id = ${info.id}`;
  db.query(sqlStr, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
    res.send({ code: 200, msg: '查询成功', data: results })
  })
}

// 删除一篇帖子
exports.deleteArticle = (req, res) => {
  const info = req.query;
  const sqlStr = `delete from articles where id = ${info.id}`;
  db.query(sqlStr, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
    res.send({ code: 200, msg: '删除成功' });
  })
}

// 发表评论
exports.comment = (req, res) => {
  const info = req.body;
  const sql = `update articles set comment = comment + 1 where id = ${info.articleId}`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
  })
  db.query(`select * from users where id = ${info.createdById}`, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
    const sqlStr = 'insert into comments set ?';
    db.query(sqlStr, { comment: info.comment, createdBy: results[0].nickname, createdById: info.createdById, time: info.time, articleId: info.articleId }, (err, results) => {
      if (err) {
        return res.send({ code: 500, msg: '未知错误，请联系管理员' });
      }
      res.send({ code: 200, msg: '评论成功' })
    })
  })
}

// 获取一篇帖子的所有评论
exports.getArticleComments = (req, res) => {
  const info = req.query;
  const sqlStr = `select * from comments where articleId = ${info.articleId}`;
  db.query(sqlStr, (err, results) => {
    if (err) {
      return res.send({ code: 500, msg: '未知错误，请联系管理员' });
    }
    res.send({ code: 200, msg: '查询成功', data: results })
  })
}